<template>
  <div class="container" :style="pageStyle">
    <div class="guideMask" @click="hideGuideMask" v-if="showGuide">
      <div
        class="guideMaskImg"
        :style="'background:url('+guideImg+') center center / contain no-repeat;'"
      ></div>
    </div>
    <div class="mask" @click="doClick"></div>
    <div id="area"></div>
    <loading :show="loading" text="加载中..."/>
    <tool-bar
      :isShow="showToolBar"
      :progress="progress"
      :fontSize="fontSize"
      @onChangeFontsize="onChangeFontsize"
      @onThemeSelect="onThemeSelect"
      @openCatalog="openCatalog"
      ref="toolBar"
    />
    <catagory :showCatagory="showCatagory" :toc="toc" @gotoPage="gotoPage"/>
    <cc-dialog
      :isShow="BuyDialog"
      @onCancel="cancelDialog"
      @onConfirm="goBuy"
      message="該內容需要購買才可解鎖閱讀"
      confirmText="立即購買"
    />
  </div>
</template>

<script>
import { getCoverURL } from "../utils/bookUtil";
import ToolBar from "../components/ReaderToolBar";
import Catagory from "../components/catagory.vue";
import CcDialog from "../components/dialog.vue";

import { Loading } from "vux";

import axios from "axios";

import ePub from "../epub/epub.js";
import jszip from "../epub/jszip.min.js";

//const ePub = window.ePub;

export default {
  data() {
    return {
      isNative: false,
      bookSrc: null,
      bookId: null,
      bookData: null,
      progress: 0,
      book: null,
      rendition: null,
      showCatagory: 0,
      toc: null,
      clientWidth: 0,
      loading: false,
      showToolBar: null,
      show: null,
      windowWidth: 500,
      windowHeight: 500,
      testTime: 0,
      toolbarIsShow: false,
      BuyDialog: false,
      fontSize: 2,
      themeName: 0,
      backgroundColor: null,
      needBuy: false,
      showGuide: true,
      guideImg: require("@/assets/image/icon/guide.png")
    };
  },
  watch: {},
  computed: {
    pageStyle() {
      if (this.backgroundColor) {
        return {
          "background-color": this.backgroundColor
        };
      } else {
        return {
          "background-color": this.$config.themes[this.themeName].color
        };
      }
    }
  },

  components: {
    Loading,
    ToolBar,
    Catagory,
    CcDialog
  },
  mounted() {
    window["dataTransmission"] = this.dataTransmission;
    try {
      native.webViewOnload();
      this.isNative = true;
      native.hideNavigation();
    } catch (error) {}

    this.windowWidth = document.body.clientWidth;
    this.windowHeight = window.innerHeight * 0.98; //document.body.clientHeight; 預留topbar位置
    this.clientWidth = document.body.clientWidth;
    this.bookSrc = this.$route.query.src || null;
    // decodeURIComponent(
    //   "http%3A%2F%2Fnowbook-info.oss-cn-hongkong.aliyuncs.com%2FLzE1NDYyMzUzNTgwOTMwMDNfMW0uZXB1Yg%3FExpires%3D1546238956%26OSSAccessKeyId%3DLTAI3MlVyHfQ7xyf%26Signature%3DyWguN9IDBTZMH%252FvZNk09GWIIKJ0%253D"
    // );
    //"http://dev.api.nowbook.sup.services/epubfiles/01/";

    //讀取客戶端緩存，判斷是否首次，顯示指引
    if (this.isNative) {
      var dataValue = native.getStorage("reader_showGuide");
      try {
        let settingObj = JSON.parse(dataValue);
        this.showGuide = false;
      } catch (error) {
        this.showGuide = true;
      }
    }

    if (!this.isNative) {
      this.loadData();
    }
  },
  methods: {
    hideGuideMask() {
      this.showGuide = false;
      let settingObj = {
        showGuide: 1
      };
      //保存設置到本地
      if (this.isNative) {
        var setData = {
          key: "reader_showGuide",
          value: JSON.stringify(settingObj)
        };
        native.setStorage(JSON.stringify(setData));
      }
    },
    dataTransmission(params) {
      try {
        let obj = JSON.parse(params);
        this.bookId = obj.id; //ID
        this.historyCfi = obj.cfi || ""; //進度
        this.limitSection = obj.limitSection || 2; //顯示張姐
        if (this.book) {
          this.book.destroy(); // 銷毀當前書籍，重新渲染
          this.rendition.clear();
          document.getElementById("area").innerHTML = ""; //清空HTML内容
        }
        this.getEbookInfo();
      } catch (error) {}
    },

    goBuy() {
      this.BuyDialog = false;
      let obj = {
        router: this.$router,
        path: "index.html#/app/buy",
        query: {
          objType: "media",
          id: this.bookId
        }
      };
      //监听窗口关闭窗口返回事件
      window["prevWindowsParams"] = this.buyCallback;
      window["closeWindowsCallback"] = this.buyCallback;
      this.GLOBAL_.ccApp.openTo(obj);
    },

    //購買回調
    buyCallback() {
      this.getEbookInfo();
      if (this.book) {
        this.book.destroy(); // 銷毀當前書籍，重新渲染
        this.rendition.clear();
        document.getElementById("area").innerHTML = ""; //清空HTML内容
      }
    },

    cancelDialog() {
      this.BuyDialog = false;
    },

    //獲取電子書的播放地址
    getPlayUrl() {
      //顯示loading
      if (this.isNative) {
        native.showLoading();
      }

      let url = this.CONFIG.FILE.GETPLAYURL;
      let postD = {
        id: this.bookId
      };
      this.GLOBAL_.ccRequest
        .doSessionAxios(url, postD, "GET", "no login")
        .then(res => {
          this.bookSrc = res.data.url;
          this.loadData();
        })
        .catch(err => {
          if (this.isNative) {
            native.showToast("獲取播放地址失敗");
            native.hideLoading(); // 隱藏loading
          }
        });
    },

    getEbookInfo() {
      native.showLoading();
      this.needBuy = false;
      let postD = {
        id: this.bookId
      };
      this.GLOBAL_.ccRequest
        .doSessionAxios(this.CONFIG.MEDIA.GET, postD, "GET", "no login")
        .then(res => {
          this.bookData = res;
          this.bookSrc = res.mediaValue;

          if (res.ebookProgress) {
            //歷史記錄
            this.historyCfi = res.ebookProgress.cfi;
            //試讀限制
          }
          if (res.salePrice > 0 && res.isBuy != 1) {
            this.limitSection = res.probation;
          } else {
            this.limitSection = null;
          }

          this.getPlayUrl(); //獲取播放地址
        })
        .catch(err => {
          //獲取多媒體數據異常
          if (this.UTILS.chackNative()) {
            native.showToast("加载数据失败");
            native.hideLoading();
          }
        });
    },

    //加載數據
    loadData() {
      //檢查是否有SRC參數
      if (!this.bookSrc) {
        if (this.isNative) {
          let obj = {
            title: "錯誤",
            message: "缺少參數",
            yesLabel: "確定",
            noLabel: ""
          };
          native.showDialog(JSON.stringify(obj));
        } else {
          this.$vux.alert.show({
            title: "错误",
            content: "缺少參數"
          });
        }
        return;
      } else {
        this.getBook();
      }
    },

    getBook() {
      axios({
        method: "GET",
        url: this.bookSrc,
        responseType: "arraybuffer"
      })
        .then(res => {
          this.testTime = new Date(); //測試渲染時間

          this.loadBook(res.data);
        })
        .catch(err => {
          native.hideLoading();
        });
    },

    //測試從本地獲取文件
    testGetLocalBook() {
      let href = window.location.href;
      let testUrl =
        window.location.href.split("/html/")[0] + "/html/files/test.epub";
      alert("测试的地址" + testUrl);
      axios({
        method: "GET",
        url: testUrl,
        responseType: "arraybuffer"
      })
        .then(res => {
          // console.log("本地文件文件下载成功！" + res);
          // this.loadBook(res.data);
        })
        .catch(err => {
          // console.log("本地文件下载失败！");
          // console.log("err", err);
        });
    },

    loadBook(url) {
      this.book = ePub();
      this.book.open(url);
      this.rendition = this.book.renderTo("area", {
        width: parseInt(this.windowWidth) + "px",
        height: parseInt(this.windowHeight) + "px"
      });

      //獲取目錄
      this.book.loaded.navigation.then(navigation => {
        //构建目录
        this.toc = navigation.toc;
      });
      this.setHook();

      this.rendition.on("relocated", locationCfi => {
        //构造进度
        let index = locationCfi.start.index;

        if (this.limitSection && index + 1 > this.limitSection) {
          //超過試讀顯示
          this.needBuy = true;
          this.BuyDialog = true;
          return;
        }

        let page = locationCfi.start.displayed.page;
        let total = locationCfi.start.displayed.total;
        this.progress = (page / total) * 100;
        let cfi = locationCfi.start.cfi;
        let progressStr = `第${index}章第${page}頁`;
        this.reportProgress(cfi, progressStr);
      });
      this.registThemes(); // 注册设置皮肤
      this.setupStyle(); //设置样式

      this.rendition.on("displayed", () => {
        if (this.isNative) {
          native.hideLoading();
        }
      });

      if (this.historyCfi) {
        //如果有播放進度，則從上次閱讀開始
        this.rendition.display(this.historyCfi);
      } else {
        this.rendition.display();
      }
    },

    //上報進度
    reportProgress(cfi, progressStr) {
      let postD = {
        operate: "play",
        objType: "media",
        objId: this.bookId,
        extraData: JSON.stringify({
          cfi: cfi,
          progress: progressStr
        })
      };
      let url = this.CONFIG.OPERATE.ADD;
      this.GLOBAL_.ccRequest
        .doSessionAxios(url, postD, "GET", "no login")
        .then(res => {})
        .catch(err => {});
    },

    setHook() {
      this.rendition.hooks.content.register(contents => {
        var loaded = Promise.all([
          contents.addStylesheet("/static/reader.css")
        ]);
        return loaded;
      });
    },

    setupStyle() {
      //读取本地缓存，是否有已选的样式参数
      this.getSetting();
      this.rendition.themes.select(this.$config.themes[this.themeName].name);
      //设置字体,默认14
      this.rendition.themes.fontSize(
        this.$config.fontsizes[this.fontSize].size + "px"
      );
      //this.backgroundColor = this.$config.themes[this.themeName].color;
    },

    //注册皮肤
    registThemes() {
      //黑色皮肤
      this.rendition.themes.register("dark", {
        body: {
          color: "#b5b5b5 !important",
          background: "#232733 "
        },
        p: {
          color: "#b5b5b5 !important"
        },
        h1: {
          color: "#b5b5b5 !important"
        },
        h2: {
          color: "#b5b5b5 !important"
        },
        h3: {
          color: "#b5b5b5 !important"
        },
        h4: {
          color: "#b5b5b5 !important"
        },
        a: {
          color: "#b5b5b5",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
      //白色
      this.rendition.themes.register("light", {
        body: { color: "#000 !important", background: "#fff" },
        p: { color: "#000 !important" },
        a: {
          color: "#000",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
      //黄色
      this.rendition.themes.register("yellow", {
        body: {
          color: "#000 !important",
          background: "#f6f3e0"
        },
        p: { color: "#000 !important" },
        a: {
          color: "#000",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
      //绿色
      this.rendition.themes.register("green", {
        body: { color: "#000 !important", background: "#cdf0d0" },
        p: { color: "#000 !important" },
        a: {
          color: "#000",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
    },

    //打开目录
    openCatalog() {
      this.$refs.toolBar.doHide();
      this.showCatagory = new Date().getTime();
    },

    //切换上一页
    prev() {
      if (this.rendition) {
        this.rendition.prev();
      }
    },
    //切换下一页
    next() {
      // console.log("需要购买", this.needBuy);

      if (!this.needBuy && this.rendition) {
        //防止点取消购买，还可以切换下一页
        this.rendition.next();
      }
    },
    //屏幕点击事件
    doClick(e) {
      //点击的X坐标
      let clickX = e.clientX;
      if (clickX < this.clientWidth / 3) {
        //点击屏幕左边1/3
        this.prev();
      } else if (clickX > (this.clientWidth * 2) / 3) {
        //点击右边1/3
        this.next();
      } else {
        this.showToolBar = new Date().getTime();
      }
    },

    onChangeFontsize(fontsize) {
      this.fontSize = fontsize;
      this.rendition.themes.fontSize(
        this.$config.fontsizes[this.fontSize].size + "px"
      );
      this.saveSettingToLocal();
    },
    onThemeSelect(theme) {
      let themeConfig = this.$config.themes[theme];
      this.themeName = theme;
      this.rendition.themes.select(themeConfig.name);
      this.saveSettingToLocal();
    },

    saveSettingToLocal() {
      let settingObj = {
        fontSize: this.fontSize,
        themeName: this.themeName
      };
      //保存設置到本地
      if (this.isNative) {
        var setData = {
          key: "reader_setting",
          value: JSON.stringify(settingObj)
        };

        native.setStorage(JSON.stringify(setData));
      }
    },

    //從本地緩存中讀取
    getSetting() {
      try {
        var dataValue = native.getStorage("reader_setting");
        let settingObj = JSON.parse(dataValue);
        this.fontSize = settingObj.fontSize;
        this.themeName = settingObj.themeName;
      } catch (error) {}
    },

    //目录跳转
    gotoPage(href) {
      this.rendition.display(href);
    }
  }
};
//
</script>

<style lang="less" scoped>
@import "~vux/src/styles/close.less";

.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.guideMask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 999;
  background: rgba(0, 0, 0, 0.4);
}

.guideMaskImg {
  width: 100vw;
  height: 100vh;
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 99;
}

#area {
  /* position: absolute; */
  //background: red;
  // width: 100%;
  // height: 90%;
  padding-top: 2vh;
}

#prev {
  left: 40px;
}

#next {
  right: 40px;
}

.contents-1 {
}
</style>
